#pragma once

#include "eventhandler.h"
#include "SOCK_Acceptor.h"
#include "reactor.h"
#include "Acceptor.h"
#include "LFThreadPool.h"
#include "LFEventHandler.h"

namespace Network{
	template <class EVENT_HANDLER> class LFAcceptor : public EventHandler
	{
		public:
			LFAcceptor<EVENT_HANDLER>(INET_Addr &addr, Reactor *reactor, LFThreadPool* threadPool) : acceptor(addr), reactor(reactor)
			{
				this->reactor = reactor;
				reactor->register_handler(this, ACCEPT_EVENT);
				this->threadPool = threadPool;
			};
	
			~LFAcceptor<EVENT_HANDLER>(void)
			{
				this->reactor->remove_handler(this, ACCEPT_EVENT);
			};
	
		virtual void HandleEvent(HANDLE handle, EventType et )
		{
			// Can only be called for an ACCEPT event.
			if( et == ACCEPT_EVENT )
			{
				SOCK_Stream clientConnection( handle );
				acceptor.accept( clientConnection );

				// create event handlers for the connection.
				EVENT_HANDLER* eventHandler = new EVENT_HANDLER(clientConnection);
				LFEventHandler* LFeventHandler = new LFEventHandler(eventHandler, threadPool);
				this->reactor->register_handler(LFeventHandler, READ_EVENT);
			}
		}

		virtual HANDLE GetHandle(void)
		{
			return acceptor.get_handle();
		}

		private:
			SOCK_Acceptor acceptor;
			Reactor *reactor;
			bool isActive;
			LFThreadPool* threadPool;
	};
}